import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Tabs } from 'antd-mobile';
import TopNav from '../../../components/topNav';
import { collectionService, handleApiResponse, handleApiError } from '../../../utils/api';
import type {
  HealthInfoCollectionItem,
  SickCircleCollectionItem,
  VideoCollectionItem
} from '../../../type';
import './index.css';

const UserFavorite: React.FC = () => {
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = useState('healthInfo');
  const [loading, setLoading] = useState(false);
  
  // 数据状态
  const [healthInfoList, setHealthInfoList] = useState<HealthInfoCollectionItem[]>([]);
  const [sickCircleList, setSickCircleList] = useState<SickCircleCollectionItem[]>([]);
  const [videoList, setVideoList] = useState<VideoCollectionItem[]>([]);

  // 分页状态
  const [healthInfoPage, setHealthInfoPage] = useState(1);
  const [sickCirclePage, setSickCirclePage] = useState(1);
  const [videoPage, setVideoPage] = useState(1);

  // 获取健康资讯收藏列表
  const fetchHealthInfoList = async (page: number = 1, append: boolean = false) => {
    try {
      setLoading(true);
      const response = await collectionService.getHealthInfoCollectionList({
        page,
        count: 10
      });
      const data = handleApiResponse<HealthInfoCollectionItem[]>(response);
      
      if (append) {
        setHealthInfoList(prev => [...prev, ...data]);
      } else {
        setHealthInfoList(data);
      }
    } catch (error) {
      console.error('获取健康资讯收藏列表失败:', error);
      // 可以添加错误提示
    } finally {
      setLoading(false);
    }
  };

  // 获取病友圈收藏列表
  const fetchSickCircleList = async (page: number = 1, append: boolean = false) => {
    try {
      setLoading(true);
      const response = await collectionService.getSickCircleCollectionList({
        page,
        count: 10
      });
      const data = handleApiResponse<SickCircleCollectionItem[]>(response);
      
      if (append) {
        setSickCircleList(prev => [...prev, ...data]);
      } else {
        setSickCircleList(data);
      }
    } catch (error) {
      console.error('获取病友圈收藏列表失败:', error);
      // 可以添加错误提示
    } finally {
      setLoading(false);
    }
  };

  // 获取健康视频收藏列表
  const fetchVideoList = async (page: number = 1, append: boolean = false) => {
    try {
      setLoading(true);
      const response = await collectionService.getVideoCollectionList({
        page,
        count: 10
      });
      const data = handleApiResponse<VideoCollectionItem[]>(response);
      
      if (append) {
        setVideoList(prev => [...prev, ...data]);
      } else {
        setVideoList(data);
      }
    } catch (error) {
      console.error('获取健康视频收藏列表失败:', error);
      // 可以添加错误提示
    } finally {
      setLoading(false);
    }
  };

  // 初始化数据
  useEffect(() => {
    fetchHealthInfoList();
  }, []);

  // Tab切换处理
  const handleTabChange = (key: string) => {
    setActiveTab(key);
    
    switch (key) {
      case 'healthInfo':
        if (healthInfoList.length === 0) {
          fetchHealthInfoList();
        }
        break;
      case 'sickCircle':
        if (sickCircleList.length === 0) {
          fetchSickCircleList();
        }
        break;
      case 'video':
        if (videoList.length === 0) {
          fetchVideoList();
        }
        break;
    }
  };

  // 格式化时间
  const formatTime = (timestamp: number) => {
    const now = Date.now();
    const diff = now - timestamp;
    const minutes = Math.floor(diff / (1000 * 60));
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (minutes < 60) {
      return `${minutes}分钟前`;
    } else if (hours < 24) {
      return `${hours}小时前`;
    } else if (days < 7) {
      return `${days}天前`;
    } else {
      return new Date(timestamp).toLocaleDateString();
    }
  };

  // 点击健康资讯项
  const handleHealthInfoClick = (item: HealthInfoCollectionItem) => {
    navigate(`/imdetail/${item.infold}`);
  };

  // 点击病友圈项
  const handleSickCircleClick = (item: SickCircleCollectionItem) => {
    navigate(`/BpatientCircle/BpatientCircleDetail?sickCircleId=${item.sickCircleId}`);
  };

  // 点击视频项
  const handleVideoClick = (item: VideoCollectionItem) => {
    navigate(`/CvideoPage?videoId=${item.videoId}`);
  };

  // 渲染健康资讯列表项
  const renderHealthInfoItem = (item: HealthInfoCollectionItem) => (
    <div key={item.id} className="collection-item" onClick={() => handleHealthInfoClick(item)}>
      <div className="item-content">
        {item.thumbnail && (
          <div className="item-image">
            <img src={item.thumbnail} alt={item.title} />
          </div>
        )}
        <div className="item-text">
          <div className="item-title">{item.title}</div>
          <div className="item-meta">
            <span className="item-time">{formatTime(item.createTime)}</span>
          </div>
        </div>
      </div>
    </div>
  );

  // 渲染病友圈列表项
  const renderSickCircleItem = (item: SickCircleCollectionItem) => (
    <div key={item.id} className="collection-item" onClick={() => handleSickCircleClick(item)}>
      <div className="item-content">
        <div className="item-text">
          <div className="item-title">{item.title}</div>
          <div className="item-disease">{item.disease}</div>
          <div className="item-meta">
            <span className="item-time">{formatTime(item.createTime)}</span>
            <span className="item-stats">
              {item.collectionNum}收藏 · {item.commentNum}评论
            </span>
          </div>
        </div>
      </div>
    </div>
  );

  // 渲染视频列表项
  const renderVideoItem = (item: VideoCollectionItem) => (
    <div key={item.id} className="collection-item" onClick={() => handleVideoClick(item)}>
      <div className="item-content">
        <div className="item-text">
          <div className="item-title">{item.title}</div>
          <div className="item-meta">
            <span className="item-time">{formatTime(item.createTime)}</span>
            <span className="item-price">{item.price}H币</span>
            <span className="item-duration">{Math.floor(item.duration / 60)}分钟</span>
          </div>
        </div>
      </div>
    </div>
  );

  return (
    <div className="user-favorite">
      <TopNav title="我的收藏" />
      
      <div className="favorite-content">
        <Tabs
          activeKey={activeTab}
          onChange={handleTabChange}
          className="favorite-tabs"
        >
          <Tabs.Tab title="健康资讯" key="healthInfo">
            <div className="tab-content">
              {healthInfoList.length > 0 ? (
                healthInfoList.map(renderHealthInfoItem)
              ) : (
                <div className="empty-state">
                  {loading ? '加载中...' : '暂无收藏的健康资讯'}
                </div>
              )}
            </div>
          </Tabs.Tab>
          
          <Tabs.Tab title="健康视频" key="video">
            <div className="tab-content">
              {videoList.length > 0 ? (
                videoList.map(renderVideoItem)
              ) : (
                <div className="empty-state">
                  {loading ? '加载中...' : '暂无收藏的健康视频'}
                </div>
              )}
            </div>
          </Tabs.Tab>
          
          <Tabs.Tab title="病友圈" key="sickCircle">
            <div className="tab-content">
              {sickCircleList.length > 0 ? (
                sickCircleList.map(renderSickCircleItem)
              ) : (
                <div className="empty-state">
                  {loading ? '加载中...' : '暂无收藏的病友圈'}
                </div>
              )}
            </div>
          </Tabs.Tab>
        </Tabs>
      </div>
    </div>
  );
};

export default UserFavorite;
